package com.enterprise.projectManager.service.implemention;

import com.enterprise.projectManager.component.UploadProperties;
import com.enterprise.projectManager.model.Appendix;
import com.enterprise.projectManager.model.Count;
import com.enterprise.projectManager.model.Project;
import com.enterprise.projectManager.rope.AppendixRope;
import com.enterprise.projectManager.rope.CountRope;
import com.enterprise.projectManager.rope.ProjectRope;
import com.enterprise.projectManager.service.AppendixService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class AppendixImpl implements AppendixService {
    private final UploadProperties uploadProperties;
    private final ProjectRope projectRope;
    private final AppendixRope appendixRope;
    private final CountServiceImpl countService;
    @Override
    public String uploadToLocal(List<MultipartFile> files, String projectId) {
        String uploadDirectory = uploadProperties.getDirectory();
        Project project = projectRope.findById(projectId).orElse(null);
        if(project == null) return "项目不存在";
        if (files.isEmpty()) {
            return "上传失败，无文件";
        }
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    // 创建文件保存路径
                    String fileName = file.getOriginalFilename();
                    String filePath = uploadDirectory + projectId + "/" + fileName;

                    // 创建目录
                    File dir = new File(uploadDirectory + projectId);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    // 保存文件
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(filePath);
                    Files.write(path, bytes);

                    // 创建 Appendix 对象并设置属性
                    Appendix appendix = new Appendix();
                    appendix.setAppendixId(countService.generalAppendixId());
                    appendix.setAppendixName(fileName);
                    appendix.setAppendixPath(filePath);
                    appendix.setAppendixSize(file.getSize());
                    appendix.setAppendixType(file.getContentType());
                    appendix.setProject(project);
                    save(appendix);

                } catch (Exception e) {
                    return "上传失败：" + e.getMessage();
                }
            } else {
                return "上传失败，请选择文件";
            }
        }

        return "上传成功";
    }

    @Override
    public Appendix save(Appendix appendix) {
        if (appendix.getAppendixId() == null)
        {
            appendix.setAppendixId(countService.generalAppendixId());
        }
        return appendixRope.save(appendix);
    }

    @Override
    public List<Resource> getDownloadUrl(String projectId) {
        List<Appendix> appendices = appendixRope.findByProjectProjectId(projectId);
        List<Resource> resources = new ArrayList<>();
        appendices.forEach(a -> {
            // 构建文件路径
            Path filePath = Paths.get(a.getAppendixPath());

            // 从文件系统中加载文件
            try {
                Resource resource = new UrlResource(filePath.toUri());
                resources.add(resource);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        });
        return resources;
    }

    @Override
    public List<String> getDownloadPath(String projectId) {
        List<Appendix> appendices = appendixRope.findByProjectProjectId(projectId);
        List<String> paths = new ArrayList<>();
        appendices.forEach(a -> {
            paths.add(a.getAppendixPath());
        });
        return paths;
    }

    @Override
    public List<Appendix> getProjectFileList(String projectId) {
        return appendixRope.findByProjectProjectId(projectId);
    }
}
